from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required


from wjContact.contacts.models import Sale
from wjContact.contacts.views.forms import SalesForm





##============================================================================##
## Methods and views which user multi-table forms
##============================================================================##


def sales_list(request):
    """ List all sales."""
    sales = Sale.objects.all()
    return render_to_response(
        'sales_list.html', 
        {'sales_list': sales},
        context_instance=RequestContext(request))    
     
def sales_edit(request, main_object_id=None, recipient_id=None, computer_id=None):
    ## <wsl> FIXME: may want to get rid of main_object_id if it is unused.
    if recipient_id:
        return  sale_to_recipient(request, recipient_id=recipient_id)
    
def sale_to_recipient(request,  recipient_id=None):
    """ """
    ## See contrib/admin/views.main.add_stage() for some ideas...   
    ## If user has hit the submit button, the request method will be 'POST'...
    ## The following works whether we are an adding form or an editing
    ## form.
    if request.method == 'POST':    
        ## We are an adding form       
        form = SalesForm(request.POST)
        ## handle_recipient_form does validation and re-rendering or directing on.               
        return handle_sales_form(request, form)          
    else:  
        ## Make an empty form with just the recipient_id set (using the initial 
        ## keyword)
        form = SalesForm(initial = {'recipient': recipient_id})
        form_instructions = "Add a new sale to recipient %s  here!" % recipient_id
        return render_to_response(
            'sales.html', 
            {
            'form' : form,
            'form_instructions': form_instructions,
            },
            context_instance=RequestContext(request)
            )                                     
sale_to_recipient = login_required(sale_to_recipient) 

def handle_sales_form(request, filled_form): 
    """
    Check that the filled form is valid, and check for duplicates. 
    
     1. If everything checks out ok: get the form to save() itself and return
        the 'save and redirect' method.
     2. If there are duplicates, instead render a page listing these.
     3. If the form data is invalid in some way, re-render the form with the
        error messages displayed, so that the user can fix them.
     """
    if not (filled_form.is_valid()):
        ## If it's not valid, render failure message
        msg = "Couldn't add new sale using the details given. Please fix the problems listed below and I'll try again :)"
        request.user.message_set.create(message=msg)
        return render_to_response('sales.html',
             {'form': filled_form}, 
             context_instance=RequestContext(request) )  
    contact = filled_form.save()
    recipient_id = filled_form.clean_data['recipient']
    computer_id = filled_form.clean_data['computer']
    msg = "Sale of computer %s to recipient %s successfully recorded." % (computer_id, recipient_id)
    request.user.message_set.create(message=msg)
    redirect_to = "http://localhost:8000/sales/"
    return HttpResponseRedirect(redirect_to)  
        


